package com.cardbaobao.cardbabyclient.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;

import com.alibaba.fastjson.JSON;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.controller.BroadcastController;
import com.cardbaobao.cardbabyclient.model.Event;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.RegularUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.UmengEventUtils;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.gyf.barlibrary.ImmersionBar;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Observable;
import rx.Subscriber;


/**
 * Description: 账号登录
 * Created by FHW
 * on 2017/6/15
 */
public class AccountLoginActivity extends BaseActivity{
    public static final String LOGIN_REQUEST_FROM_S="loginRequestFrom";

    private final int RegisterCode = 1001;
    private final int MobileLoginCode = 1002;

    public static String JUM_TYPE_I = "jumType";

    @BindView(R.id.tw_toolbar)
    TitleBar tw_toolbar;

    @BindView(R.id.edtext_phone)
    EditText mPhoneEd;//
    @BindView(R.id.edtext_pass)
    EditText mPassword;
    @BindView(R.id.commit_data)
    Button mLogin;
    @BindView(R.id.cb_pwd_state)
    CheckBox cb_pwd_state;

    private int type = -1;

    private String mPhone = "";

    private int jumType = -1;//0-首页 1-信用卡 2-贷款 3-发现 4-我的

    private String loginRequestFrom;//请求登录的页面

    @Override
    protected void initView(Bundle savedInstanceState) {
        ImmersionBar.with(this).statusBarDarkFont(true,Constant.STATUS_BAR_FONT_ALPHA).keyboardEnable(true).init();
        initIntent();

        mCurrentPageId= Self.Page.app_account_login_page;
        loginRequestFrom=getIntent().getStringExtra(LOGIN_REQUEST_FROM_S);

        type = getIntent().getIntExtra("type", -1);
        jumType = getIntent().getIntExtra(JUM_TYPE_I, -1);

        if (mApplication.getUser() != null && !TextUtils.isEmpty(mApplication.getUser().getPhone())) {
            mPhone = mApplication.getUser().getPhone();
            if (mPhone.length() == 11) {
                mPhoneEd.setText(mPhone.substring(0, 3) + "****" + mPhone.substring(7));
                mPhoneEd.setSelection(mPhoneEd.getText().length());
            }
        }
        mPhoneEd.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                mPhone = s.toString();
                setLoginBtState();
            }
        });

        tw_toolbar.setRightViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        cb_pwd_state.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    mPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                } else {
                    mPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
                }
            }
        });
    }

    @OnTextChanged({R.id.edtext_pass})
    public void afterPwdChange(Editable s){
        setLoginBtState();
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    private void setLoginBtState(){
        if(mPhoneEd.getText().length()>0&&mPassword.getText().length()>0){
            mLogin.setEnabled(true);
        }else{
            mLogin.setEnabled(false);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_account_login;
    }

    @Override
    public void onResume() {
        super.onResume();
        UmengEventUtils.pageEvent(mContext,
                ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.event_0x02f));
        GoogleAnalyticsUtil.setScreenName(Google.ACCOUNT_LOGIN);
    }

    /**
     * 账号登录
     */
    private void userLoginIn(String phone) {
        String msg = "";
        //验证手机号码
        if (TextUtils.isDigitsOnly(phone) && RegularUtil.isPhoneNumber(phone)) {
            String pwd = mPassword.getText().toString().trim();
            if (TextUtils.isEmpty(pwd)) {
                msg = ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_input_pwd_tip);
            } else if (pwd.length() < 6) {
                msg = "密码最少为6位";
            } else {
                loginData(phone, pwd);
                GoogleAnalyticsUtil.setScreenAction(Google.CAREGORY_ORD, Google.ACTION_ACCOUNT_LOGIN);
            }
        } else {
            msg = ApplicationHelper.
                    getApplicationContext().
                    getString(R.string.string_input_phone_tip);
        }
        if (!TextUtils.isEmpty(msg)) {
            ToastUtil.showToast(msg);
        }
    }

    /**
     * 请求登录接口
     *
     * @param phone 账号
     * @param password 密码
     */
    private void loginData(final String phone, String password) {
        showProgressDialog(false, "正在登录");
        Observable<String> observable= Api.login(phone,password);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                dismissProgressDialog();
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                try {
                    JSONObject object = new JSONObject(s);
                    if (object.optInt("code") == 1) {
                        UserInfo userInfo = JSON.parseObject(object.optJSONObject("msg").opt("data").toString(), UserInfo.class);
                        if (userInfo != null) {
                            userInfo.setPhone(phone);
                            mApplication.setUser(userInfo);
                            new BroadcastController(mContext).notifyUserLogin();
                            Intent intent = getIntent();
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                            EventBus.getDefault().post(new Event.LoginSucNotify(jumType));
                        } else {
                            ToastUtil.showToast("登录失败");
                        }
                    } else {
                        ToastUtil.showToast(object.optString("msg"));
                    }
                } catch (Exception e) {
                    ToastUtil.showToast("登录失败");
                }
            }
        });
    }

    //覆盖基类方法
    public void showProgressDialog(boolean isTouchHide, String showText) {
        super.showProgressDialog(isTouchHide,showText);
        mLogin.setEnabled(false);
        mPhoneEd.setEnabled(false);
        mPassword.setEnabled(false);
    }

    //覆盖基类方法
    public void dismissProgressDialog() {
        super.dismissProgressDialog();
        mLogin.setEnabled(true);
        mPhoneEd.setEnabled(true);
        mPassword.setEnabled(true);
    }

    @OnClick({R.id.tv_get_back_pwd,R.id.commit_data,R.id.tv_mobile_login,R.id.tv_register})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_get_back_pwd:
                //找回密码
                startActivity(new Intent(mContext, GetBackPasswordActivity.class));
                break;
            case R.id.commit_data:
                //登录
                userLoginIn(mPhone);
                break;
            case R.id.tv_mobile_login:
                //手机验证登录
                Intent mobileLoginIntent=new Intent(mContext,MobileLoginActivity.class);
                mobileLoginIntent.putExtra(LOGIN_REQUEST_FROM_S,loginRequestFrom);
                startActivityForResult(mobileLoginIntent, MobileLoginCode);
                break;
            case R.id.tv_register:
                Intent registerIntent=new Intent(mContext,RegisterActivity.class);
                registerIntent.putExtra(LOGIN_REQUEST_FROM_S,loginRequestFrom);
                startActivityForResult(registerIntent, RegisterCode);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case RegisterCode:
                    break;
                case MobileLoginCode:
                    Intent intent = getIntent();
                    setResult(Activity.RESULT_OK, intent);
                    break;
            }
            finish();
            EventBus.getDefault().post(new Event.LoginSucNotify(jumType));
        }
    }

    @Override
    public void finish() {
        super.finish();
        if (type != -1) {
            //关闭activity动画显示
            this.overridePendingTransition(R.anim.activity_in_top, R.anim.activity_out_bottm);
        }
    }
}
